import { alpha, Box } from "@mui/material";
import React, { useEffect, useState } from "react";
export type TablePickerValue = Array<number> | undefined;
export interface TablePickerProps {
  maxRow?: number; //最大行数
  maxColumn?: number; //最大列数
  value?: Array<number>;
  header?: React.ReactElement | null;
  footer?: React.ReactElement | null;
  onChange?: (value: TablePickerValue) => void;
  onLoseFoucs?: (value: TablePickerValue) => void; //当失去焦点时
  clearOnLoseFocus?: boolean; //失去焦点时清空选值
}
const TablePicker = ({ maxRow = 10, maxColumn = 10, onChange, value, clearOnLoseFocus, footer, header, onLoseFoucs }: TablePickerProps) => {
  const cellitems = Array.from({ length: maxColumn * maxRow });
  const [activedCell, setActivedCell] = useState<TablePickerValue>();
  useEffect(() => {
    setActivedCell(value);
  }, [value, setActivedCell]);
  return (
    <Box
      className={"table-picker-root"}
      onMouseLeave={() => {
        clearOnLoseFocus && setActivedCell(undefined);
        onLoseFoucs && onLoseFoucs?.(activedCell);
      }}
      sx={{ p: 2, backgroundColor: "white", borderRadius: 2 }}
    >
      {header !== undefined ? header : <Box sx={{ fontWeight: 600, pb: 1, fontSize: "0.9em" }}>{!activedCell ? "插入表格" : `${activedCell?.[0] ?? 0}x${activedCell?.[1] ?? 0} 表格`}</Box>}
      <Box
        sx={{
          aspectRatio: 1 / 1,
          display: "grid",
          gridTemplateColumns: "repeat(10,1fr)",
          gridTemplateRows: "repeat(10,1fr)",
          gap: "4px",
          alignItems: "center",
        }}
      >
        {cellitems?.map((item, index) => {
          ++index;
          const [x, y] = [Math.ceil(index / maxColumn), index % maxColumn || 10];
          const inRange = x <= (activedCell?.[0] || 0) && y <= (activedCell?.[1] || 0);
          return (
            <Box
              key={index}
              onMouseEnter={() => {
                setActivedCell([x, y]);
              }}
              onClick={() => {
                onChange && onChange([x, y]);
              }}
              sx={{
                p: 0.5,
                cursor: "pointer",
                borderRadius: 0.5,
                height: "100%",
                boxSizing: "border-box",
                border: "1px solid white",
                borderColor: inRange ? (theme) => theme.palette.primary.main : "#e2e6ed",
                backgroundColor: inRange ? (theme) => alpha(theme.palette.primary.main, 0.3) : undefined,
                color: inRange ? "red" : undefined,
              }}
            ></Box>
          );
        })}
      </Box>
      {footer}
    </Box>
  );
};

export default TablePicker;
